package apps.sim.core;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import com.sun.net.httpserver.HttpExchange;

public interface IHandler {

	byte[] handle(HttpExchange exchange, String context) throws Exception;

	String getDescription();

	IHandlerConfig getHandlerConfiguration();

	void setHandlerConfiguration(IHandlerConfig config);

	String getContentType();

	public static interface IHandlerConfig {

		String ARG_SEPARATOR_REGEX = "_\\|\\|_";

		String ARG_SEPARATOR = "_||_";

		String asString();

		void fromString(String string);

		IHandlerConfig cloneInstance();
	}

	@Retention(RetentionPolicy.RUNTIME)
	public static @interface Config {
		String descrition();
	}

	@Retention(RetentionPolicy.RUNTIME)
	public static @interface Action {
		String descrition();
	}

	public static class Util {
		public static byte[] readDataAsString(InputStream in) throws IOException {
			final StringBuilder builder = new StringBuilder();
			final InputStreamReader reader = new InputStreamReader(in);
			final BufferedReader bReader = new BufferedReader(reader);
			String str;
			while ((str = bReader.readLine()) != null) {
				builder.append(str);
				builder.append("\n");
			}
			return builder.toString().getBytes();
		}

		public static byte[] readDataAsByte(InputStream in) throws IOException {
			final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			int count = 0;
			while ((count = in.read()) != -1) {
				bytes.write(count);
			}
			return bytes.toByteArray();

		}

		public static Map<String, String> extractParams(URI uri) {
			final Map<String, String> map = new HashMap<String, String>();
			if (uri.getQuery() != null) {
				final String[] split = uri.getQuery().split("&");
				for (String string : split) {
					// string = string.replaceAll("\\?", "");
					final int indexOf = string.indexOf("=");
					if (indexOf != -1) {
						map.put(string.substring(0, indexOf), string.substring(indexOf + 1));
					} else {
						map.put(string, "");
					}
				}
			}
			return map;
		}

		public static InputStream getAsString(Exception e) {
			final StringBuilder builder = new StringBuilder();
			builder.append(e.getMessage());
			builder.append("\n");
			final StackTraceElement[] stackTrace = e.getStackTrace();
			for (StackTraceElement stackTraceElement : stackTrace) {
				builder.append("\n");
				builder.append(stackTraceElement);
			}
			return new ByteArrayInputStream(builder.toString().getBytes());
		}
	}
}
